import { defineStore } from 'pinia'
import { defaultUser, fetchProfileInfoByToken } from '@/services/api'
import { getCache, setCache } from '@/utils/cache'
import { USER_INFO_KEY } from '@/enums/cacheEnum'

interface UserInfoState {
  userInfo: ApiModels.base.ApplicationUserInfo
}

const defaultUserInfo: ApiModels.base.ApplicationUserInfo = { ...defaultUser, role: '业务员' }

export const useUserStore = defineStore({
  id: 'user',
  state: (): UserInfoState => ({ userInfo: { ...defaultUserInfo } }),
  getters: {
    getUserInfo: state => state.userInfo,
  },
  actions: {
    initUserInfo() {
      const data = getCache<ApiModels.base.ApplicationUserInfo>(USER_INFO_KEY) || { ...defaultUserInfo }
      this.userInfo = { ...data }
    },
    async getUserInfoAsync(token: string) {
      const { error, data } = await fetchProfileInfoByToken(token)
      if (error)
        return Promise.reject(error)
      setCache(USER_INFO_KEY, data)
      return Promise.resolve(data)
    },
  },
})
